/** @format */

const esbuild = require('esbuild')
const { resolve } = require('path')
const { writeFileSync, accessSync } = require('fs')
const mkdirp = require('mkdirp')
const packageJson = require('./package.json')
const DIST_DIR = resolve(__dirname, '../cloudfunctions')

const { PUBLISH_PLATFORM } = process.env
const SERVER_PATH = resolve(DIST_DIR, `./${packageJson.cloudName}`)

const enrtyPath = './src/index.ts'

const cloudJson = {
  runtime: 'nodejs8',
  version: '1.0'
}

;(async () => {
  await mkdirp(resolve(SERVER_PATH))
  esbuild.buildSync({
    entryPoints: [enrtyPath],
    bundle: true,
    outfile: `${SERVER_PATH}/app.js`,
    minify: true,
    sourcemap: true,
    platform: 'node',
    target: 'node18'
  })

  // write(resolve(SERVER_PATH, 'index.js'), code)
  // write(resolve(SERVER_PATH, 'index.js.map'), map)
  writePackageJson()
  writeTaobao()
  console.log('packed ~')
})()

function writeTaobao() {
  writeMiniProjectJson()
  writeAppJson()
  writeEntry()
  write(resolve(SERVER_PATH, 'cloud.json'), JSON.stringify(cloudJson, null, 2))
}

function writePackageJson() {
  const copyPackJson = { ...packageJson }
  delete copyPackJson.dependencies
  delete copyPackJson.devDependencies
  delete copyPackJson.optionalDependencies

  write(resolve(SERVER_PATH, 'package.json'), JSON.stringify(copyPackJson, null, 2))
}

function writeMiniProjectJson() {
  const miniProjectJson = {
    exclude: ['server/**']
  }
  write(resolve(DIST_DIR, 'mini.project.json'), JSON.stringify(miniProjectJson, null, 2))
}

function writeAppJson() {
  const appJson = {
    pages: ['pages/index/index']
  }
  write(resolve(DIST_DIR, 'app.json'), JSON.stringify(appJson, null, 2))
}

function writeEntry() {
  const code = `
    const fns = require('./app.js').default
    module.exports = fns
  `
  write(resolve(SERVER_PATH, 'index.obj.js'), code)
}

function write(file, data) {
  writeFileSync(file, data)
}
